package com.yitong.equipment.ui

import android.annotation.SuppressLint
import android.content.Intent
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.os.Message
import android.text.TextUtils
import android.util.Log
import android.view.View
import android.view.Window
import android.view.WindowManager
import com.blankj.utilcode.util.ActivityUtils
import com.blankj.utilcode.util.SPUtils
import com.blankj.utilcode.util.ToastUtils
import com.yitong.equipment.base.BaseActivity
import com.yitong.equipment.constant.Constants
import com.yitong.equipment.databinding.ActivityMainBinding
import com.yitong.equipment.ext.initConfig
import com.yitong.equipment.ui.viewmodel.WelcomeViewModel
import com.yitong.equipment.view.DialogFactory

open class WelcomeActivity : BaseActivity<WelcomeViewModel, ActivityMainBinding>() {
    init {
        initConfig("com.yitong.ai", 2022010100, "1.0.9")
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        requestWindowFeature(Window.FEATURE_NO_TITLE)
        super.onCreate(savedInstanceState)
        window.addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN)
        initViewModel() //版本升级后或第一次安装app，弹窗隐私政策
        if (TextUtils.isEmpty(SPUtils.getInstance().getString(Constants.SharePreKey.KEY_PRIVACY))) {
            handler.postDelayed({
                if (ActivityUtils.isActivityAlive(this@WelcomeActivity)) {
                    DialogFactory(this@WelcomeActivity).showPrivacyDialog {
                        SPUtils.getInstance().put(
                            Constants.SharePreKey.KEY_PRIVACY,
                            Constants.SharePreKey.KEY_PRIVACY
                        )
                        initView()
                    }
                }
            }, 1000)
        } else {
            initView()
        }
    }

    private fun initView() {
        viewModel.getConfig()
        viewModel.welData.observe(this, {
            if (it) {
                handler.sendEmptyMessageDelayed(0, 1500)
            }
        })
    }

    @SuppressLint("HandlerLeak")
    private val handler: Handler = object : Handler(Looper.myLooper()!!) {
        override fun handleMessage(msg: Message) {
            super.handleMessage(msg)
            if (msg.what == 0) {
                startActivity(Intent(this@WelcomeActivity, MainTabActivity::class.java))
                finish()
            }
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        handler.removeMessages(0)
    }
}